<template>
  <q-page
    :style="{
      backgroundImage: (bg && $q.screen.gt.xs) ? `url(${ bg })` : '',
      backgroundAttachment: 'fixed',
      backgroundPosition: 'center'
    }"
  >
    <q-scroll-observer @scroll="handleScrolled" />
    <div class="page-nav row justify-center bg-white" :class="{'border-bottom-1-eee': $slots.nav}">
      <div
        v-if="$q.screen.lt.md && direction !== 'down'"
        class="bg-white col-12"
        :class="{'fit-nav shadow-light-1': direction === 'up'}"
      >
        <a-search v-if="!searchDisabled"></a-search>
      </div>
      <div
        class="col-12 row justify-center bg-white"
        :class="{'fit-nav shadow-1': direction === 'down'}"
        :style="{'box-shadow': direction === 'down' ? '0 1px 3px #ddd' : 'none'}"
      >
        <div class="col-xl-8 col-lg-10 col-md-12 col-sm-12">
          <slot name="nav"></slot>
        </div>
      </div>
    </div>
    <slot name="bar"></slot>
    <div class="row justify-center q-pb-xl" :class="{'q-mt-lg': !$slots.nav && $q.screen.gt.md, 'q-mt-md': $slots.nav}">
      <div class="col-xl-8 col-lg-10 col-md-12 col-sm-12 col-xs-12">
        <slot></slot>
      </div>
    </div>
  </q-page>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'aPage',
  props: {
    searchDisabled: {
      type: Boolean,
      required: false,
      default: false
    },
    bg: {
      type: String,
      required: false,
      default: ''
    }
  },
  data () {
    return {
      direction: null,
      scrollEventFired: false
    }
  },
  created () {
    if (process.env.NODE_ENV === 'development') {
      window.page = this
    }
  },
  computed: {
    ...mapState(['unreadNotifyCount'])
  },
  watch: {},
  methods: {
    handleScrolled ({ position, direction, directionChanged, inflexionPosition }) {
      const elementHeight = this.$el.offsetHeight

      if (position === 0 && direction === 'down' && directionChanged === false && inflexionPosition === 0) {
        this.$store.commit('setScrollStatus')
      } else {
        if (position < 100) {
          this.direction = null
        } else {
          this.direction = direction === 'down' ? 'down' : 'up'
        }

        this.$store.commit('setScrollStatus', {
          position,
          direction,
          directionChanged,
          inflexionPosition,
          tabNavEnabled: this.$slots.nav
        })
      }

      if (direction === 'up') {
        return null
      }

      if (elementHeight - this.$q.screen.height - position < 50) {
        if (this.scrollEventFired === false) {
          this.scrollEventFired = true

          this.$root.$emit('scrollBottom')
        }
      } else {
        this.scrollEventFired = false
      }
    }
  }
}
</script>

<style lang="stylus">
.page-nav
  .fit-nav
    position fixed
    left 0
    right 0
    z-index 1000
</style>
